package com.tushen.web;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * Created by likun on 2020/8/2.
 */
public class UserInterceptor implements HandlerInterceptor,Filter {
    private final String userName = "username";
    //拦截前处理


    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse response2, FilterChain filterChain) throws IOException, ServletException {
//    System.out.println("filter："+((HttpServletRequest)servletRequest).getRequestURI());
//    HttpServletResponse response=(HttpServletResponse)response2;
//    response.setHeader("Access-Control-Allow-Origin", "*");
//    response.setHeader("Access-Control-Allow-Credentials", "true");
//    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
//    response.setHeader("Access-Control-Max-Age", "3600");
//    response.setHeader("Access-Control-Allow-Headers", "Origin,Authorization,X-Requested-With,Accept,Content-Type,Access-Token");
//    response.setHeader("Access-Control-Expose-Headers", "*");
        filterChain.doFilter(servletRequest,response2);
    }

    public void destroy() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {

//    response.setHeader("Access-Control-Allow-Origin", "*");
//    response.setHeader("Access-Control-Allow-Credentials", "true");
//    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
//    response.setHeader("Access-Control-Max-Age", "3600");
//    response.setHeader("Access-Control-Allow-Headers", "Origin,Authorization,X-Requested-With,Accept,Content-Type,Access-Token");
//    response.setHeader("Access-Control-Expose-Headers", "*");
        Object sessionObj = request.getSession().getAttribute(userName);
        if(sessionObj!=null) {
            return true;
        }
        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
//    		System.out.println("post拦截："+httpServletRequest.getRequestURI());

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
//		System.out.println("after拦截："+httpServletRequest.getRequestURI());

    }



}

